import {started} from '../start';
import {getAppChanges} from "../applications/app";
import {toLoadPromise} from '../lifecycles/load'
import {toUnmountPromise} from '../lifecycles/unmount'
import {toBootstrapPromise} from "../lifecycles/bootstrap";
import {toMountPromise} from "../lifecycles/mount";
import './navigator-events';

export function reroute(){
  const {appsToLoad, appsToMount, appsToUnmount} = getAppChanges();
  console.log('getAppChanges --- --- --- appsToLoad, appsToMount, appsToUnmount:',appsToLoad, appsToMount, appsToUnmount);

  if (started) {
    console.log('调用 singleSpa.start 或则 singleSpa.start 已调用过');
    // app装载
    return performanceChanges(); //根据路径来装载应用
  }else {
    console.log('调用 singleSpa.registerApplication');
    // 注册应用时 需要预先加载
    return loadApps(); //预加载应用
  }

  //预加载应用
  //就是获取到子应用的bootstrap、mount和unmount方法放到app上
  async function loadApps(){
    const apps = await Promise.all(appsToLoad.map(toLoadPromise));

    console.log('loadApps apps:',apps);
  }


  //先卸载不需要的应用
  //再去加载需要的应用
  async function performanceChanges(){
    const unmountPromises = appsToUnmount.map(toUnmountPromise); //需要去卸载的app

    appsToLoad.map(async app => {
      app = await toLoadPromise(app);
      app = await toBootstrapPromise(app)
      //todo 先切到app1，在app1还没有准备挂载时, 又切到了app2, 此时应该不再挂载app1
      return await toMountPromise(app);
    });

    // 可能是前面已经调过 loadApps 的 （即 singleSpa.registerApplication, 但还没 singleSpa.start
    appsToMount.map(async app => {
      app = await toBootstrapPromise(app)
      return await toMountPromise(app);
    })
  }
}
